package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.service.ArticleStaticPageService;
import com.heima.article.service.IApArticleConfigService;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.wemedia.pojos.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author 21236
 */
@Component
@Slf4j
public class ArticleConsumerListener {

    @Autowired
    private ArticleStaticPageService articleStaticPageService;

    @Autowired
    private IApArticleConfigService articleConfigService;

    @KafkaListener(topics = "article-enable-topic")
    public void articleEnableMessage(String message) {
        if (!StringUtils.isEmpty(message)) {
            WmNews wmNews = JSON.parseObject(message, WmNews.class);
            Short enable = wmNews.getEnable();
            Long articleId = wmNews.getArticleId();
            articleConfigService.update(new LambdaUpdateWrapper<ApArticleConfig>()
                    .eq(ApArticleConfig::getArticleId, articleId)
                    .set(ApArticleConfig::getIsDown, enable));

            //审核成功或上架
            if (enable == 1) {
                try {
                    articleStaticPageService.generateStaticPage(articleId);
                } catch (Exception e) {
                    log.error("文章静态页面生成失败，人工处理", e);
                }
            } else if (enable == 0) {
                //下架
                articleStaticPageService.removeStaticPage(articleId);
            }

        }
    }
}
